

// 获取随机字符串
export function getRandomString(len = 11) {
  //toString(36) 最多有11位数
  if (len > 11) {
    return getRandomString(11) + getRandomString(len - 11);
  } else {
    return (
      Math.random().toString(36)
        .substring(2, len)
        .padEnd(len, '0'))
  }
}

//返回随机数
export function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

//深度克隆
export function deepClone(obj, clonedObjects = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  if (clonedObjects.has(obj)) {
    return clonedObjects.get(obj)
  }

  if (obj instanceof Date) {
    return new Date(obj.getTime())
  }

  const clonedObj = Array.isArray(obj) ? [] : {}

  clonedObjects.set(obj, clonedObj)

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key], clonedObjects)
    }
  }
  return clonedObj
}

//递归拼接菜单
//还可以根据parentId 来递归，推荐parentId来递归
export function compose(items, copyMenu) {
  if (items.children && items.children.length > 0) {
    items.children.forEach((child) => {
      let moreData = copyMenu.find((item) => item.id === child.id)
      if (moreData && moreData.children.length == 0) {
        copyMenu = copyMenu.filter((item) => item.id !== moreData.id)
      } else if (moreData && moreData.children.length > 0) {
        moreData.children.forEach((child2) => {
          let moreData2 = copyMenu.find((item) => item.id === child2.id)
          if (!child.children) child.children = []
          if (moreData2) child.children.push(child2)
          if (moreData2 && moreData2.children.length > 0) {
            copyMenu = compose(child, copyMenu)
          } else if (moreData2) {
            copyMenu = compose(moreData2, copyMenu)
          }
          copyMenu = copyMenu.filter((item) => item.id !== moreData.id)
        })
      } else {
        items.children = items.children.filter((item) => item.id !== child.id)
      }
    })
  } else if (items.first_menu == 0 && items.children && items.children.length == 0) {
    copyMenu = copyMenu.filter((item) => item.id !== items.id)
  }
  return copyMenu
}